#!/bin/bash
TARGET_SERVER=$1
TARGET_PORT=$2
TARGET_DEVICE=$3

COUNT=0
MAJOR=0
MINOR=0

function getNportMapDevice() {
	while read line
	do
		server=$(echo $line | awk '{print $2}')
		if [ ! -z "$server" ] && [ $server == $TARGET_SERVER ]; then
			COUNT=`expr $COUNT + 1`
			if [ $COUNT == $TARGET_PORT ]; then
				NPORT_DEVICE_NAME=$(echo $line | awk '{print $7}')
			fi
		fi
	done</home/coder/driver/npreal2d.cf
}

function getMajorMinor() {
	cd /home/coder/dev
	MAJOR=$(ls -la $NPORT_DEVICE_NAME | awk '{print $5}')
	MAJOR=${MAJOR%,*}
	MINOR=$(ls -la $NPORT_DEVICE_NAME | awk '{print $6}')
}

function removeUnusedDevices() {
	rm -rf /dev/ttyS*
}

function createDevice() {
	rm -rf /dev/$TARGET_DEVICE
	echo "run: mknod /dev/$TARGET_DEVICE c $MAJOR $MINOR"
	mknod /dev/$TARGET_DEVICE c $MAJOR $MINOR
}

# step 1：通过输入参数TARGET_SERVER， TARGET_PORT，查找目标设备对应的nport设备名
getNportMapDevice
if [ -z $NPORT_DEVICE_NAME ]; then
	echo "未找到nport映像设备！"
	exit 1
else 
	echo "device = $NPORT_DEVICE_NAME"
fi
# step 2: 执行 'ls -la'，从而获得目标设备的Major, Minor编号
getMajorMinor
if [ $MAJOR == 0 ] && [ $MINOR == 0 ]; then
	echo '未找到设备的major & minor 编号！'
	exit 1
else 
	echo "MAJOR, MINOR = $MAJOR , $MINOR"
fi
# step 3：删除旧的ttyS0，使用Major, Minor编号创建新的ttyS0
createDevice
if [ -c "/dev/$TARGET_DEVICE" ]; then
	chmod 666 /dev/$TARGET_DEVICE
	echo 'done！'
	exit 0
else
	echo 'failed！'
	exit 1
fi
